package com.cxdr.awsips.analysis.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;

import com.cxdr.awsips.analysis.logger.LogFactory;
/**
 * 系统配置�? * @author pugang
 *
 */
public class SystemConfig {
	private static final Properties properties = new Properties();
	private static final String CONFIG_FILE_NAME = "bin\\system-config.properties";
	private static Logger logger =LogFactory.makeNewLogger(SystemConfig.class);
	private static void validate() throws Exception{
		Set<Object> keys = properties.keySet();
		for(Object ko:keys){
			String key = (String)ko;
			if(key.startsWith("path.")){
				File path = new File(properties.getProperty(key));
				if(!path.isDirectory()){
					path.mkdirs();
				}
			}
			if(key.startsWith("file.")){
				File file = new File(properties.getProperty(key));
				if(!file.isFile()){
					logger.error("文件没有找到  key:"+key+"||value:"+properties.getProperty(key));
					throw new Exception("文件没有找到  key:"+key+"||value:"+properties.getProperty(key));
				}
			}
			if(key.startsWith("num.")){
				String value = properties.getProperty(key);
				if(!NumberUtils.isNumber(value)){
					logger.error("不是正确的数字格式 key:"+key+"||value:"+value);
					properties.setProperty(key, "-1");
				}
			}
		}
	}
	public static void load() throws Exception{
		String fileName=System.getProperty("user.dir")+ File.separator + CONFIG_FILE_NAME;
		try {
			properties.load(new InputStreamReader(new FileInputStream(fileName), Charset.forName("UTF-8")));
			validate();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void store(){
		try {
			properties.store(new FileOutputStream(System.getProperty("user.dir")
						+ File.separator + CONFIG_FILE_NAME),null);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void setAll(Properties pro) {
		properties.clear();
		properties.putAll(pro);
	}

	public static void set(String key, String value) {
		properties.setProperty(key, value);
	}

	public static String get(String key) {
		return properties.getProperty(key);
	}
	public static Properties getAll(){
		return properties;
	}
	public static void main(String[] args) throws Exception {
		load();
		System.out.println(get("str.file-last-line"));
	}
}
